<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="订单号" prop="cardOrderNumber">
              <el-input v-model="queryParams.cardOrderNumber" placeholder="请输入订单号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="拼团编码" prop="collageCode">
              <el-input v-model="queryParams.collageCode" placeholder="请输入拼团编码" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="sendPhone">
              <el-input v-model="queryParams.sendPhone" placeholder="请输入收货手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="玩家号" prop="userInviteCode">
              <el-input v-model="queryParams.userInviteCode" placeholder="请输入玩家号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="卡密" prop="carmiInfo">
              <el-input v-model="queryParams.carmiInfo" placeholder="请输入卡密" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="拼团名称" prop="collageName">
              <el-input v-model="queryParams.collageName" placeholder="请输入拼团名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
<!--      <template #header>-->
<!--        <el-row :gutter="10" class="mb8">-->
<!--            <el-button type="warning" plain icon="Download" @click="handleExport" >导出</el-button>-->
<!--          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>-->
<!--        </el-row>-->
<!--      </template>-->
      <div style="margin-top: -15px;">
        <el-tabs v-model="queryParams.logisticsStatus" type="card" @tab-change="handleQuery">
          <el-tab-pane label="全部" name="-1"></el-tab-pane>
          <el-tab-pane label="待发货" name="2"></el-tab-pane>
          <el-tab-pane label="待收货" name="3"></el-tab-pane>
          <el-tab-pane label="已完成" name="4"></el-tab-pane>
        </el-tabs>
      </div>
      <div class="hidden-table-header" style="background: #F0F0F0">
        <el-table :row-class-name="'hidden-row'" border :data="[{}]" :show-header="true"
                  :header-cell-style="{ background: '#fafafa' }" style="width: 100%;" @tab-change="handleQuery">
          <el-table-column label="商品信息" align="center" min-width="18%" />
          <el-table-column label="玩家信息" align="center" min-width="20%" />
          <el-table-column label="发货数量" align="center" min-width="13%" />
          <el-table-column label="类别" align="center" min-width="8%" />
          <el-table-column label="运费" align="center" min-width="8%" />
          <el-table-column label="收货信息" align="center" min-width="20%" />
          <el-table-column label="物流信息" align="center" min-width="15%"/>
          <el-table-column label="操作" align="center" min-width="10%" />
        </el-table>
      </div>
      <div v-for="(logistics, index) in orderLogisticsList" :key="index">
        <div class="main-order-header">
          <div style="margin-left: 10px">订单号：<span type="primary" style="color:#1a4fa9;"> {{
              logistics.cardOrderNumber }} </span></div>
          <div style="margin-left: 10px">拼团编码：<span type="primary" style="color:#945dd9;"> {{
              logistics.collageCode }} </span></div>
          <div style="margin-left: 20px"><el-tag type="success">提货时间：<span>{{ logistics.createTime }}</span></el-tag></div>
          <div style="margin-left: 20px" v-if="logistics.shipTime != null"><el-tag>发货时间：<span>{{ logistics.shipTime }}</span></el-tag></div>
          <div style="margin-left: 20px" v-if="logistics.receivedTime != null"><el-tag type = "danger">收货时间：<span>{{ logistics.receivedTime }}</span></el-tag></div>
        </div>
        <div>
          <el-table border :show-header="false" :data="[logistics]" style="width: 100%"
                    :header-cell-style="{ background: '#F0F0F0' }">
            <el-table-column label="商品信息" align="left" min-width="18%">
              <template #default="scope">
                <div>
                  <el-row :gutter="24" style="align-items: center;">
                    <el-col :span="24">
                      <image-preview :src="scope.row.collageImagePath" width="130px" height="90px"></image-preview>
                    </el-col>
                  </el-row>
                </div>
                <div>
                  <span style="color: #945dd9;">名称:  {{ scope.row.cardCollageName }} </span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="玩家信息" align="center" min-width="20%">
              <template #default="scope">
                <el-row :gutter="24">
                  <el-col :span="10">
                    <image-preview :src="scope.row.headPortrait" width="100px" height="100px"></image-preview>
                  </el-col>
                  <el-col :span="14">
                    <div>
                      <span >玩家号: {{ scope.row.userInviteCode }}</span>
                    </div>
                    <div style="margin-top: 25px">
                      <span >昵称: {{ scope.row.nickName }}</span>
                    </div>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="数量" align="center" min-width="13%">
              <template #default="scope">
                  <span style="color: #E65D6E">发货数量： x {{ scope.row.count }}</span>
              </template>
            </el-table-column>
            <el-table-column label="类别" align="center" min-width="8%">
              <template #default="scope">
                <div>
                  <dict-tag :options="logistics_source" :value="scope.row.logisticsSource" />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="运费 " align="center" min-width="8%">
              <template #default="scope">
                <span v-if="scope.row.orderFreight != null && scope.row.orderFreight > 0" style="color: #251eff">运费： x {{ scope.row.orderFreight }}</span>
                <span v-else style="color: #251eff" >包邮</span>
              </template>
            </el-table-column>
            <el-table-column label="收货信息" header-align="center" align="left" min-width="20%">
              <template #default="scope">
                <div>
                  收货人：{{ scope.row.sendName }}
                </div>
                <div style="margin-top: 5px">
                  手机号：{{ scope.row.sendPhone }}
                </div>
                <div style="margin-top: 5px">
                  地址：{{ scope.row.userAddressInfo }}
                </div>
              </template>
            </el-table-column>
            <el-table-column  label="物流信息" min-width="15%" header-align="center" align="left" >
              <template #default="scope">
                <div>
                  物流公司：{{ scope.row.expressageCompany }}
                </div>
                <div style="margin-top: 5px">
                  单号：{{ scope.row.expressageNumber }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" min-width="10%">
              <template #default="scope">
                <div>
                  <el-button v-if="scope.row.logisticsStatus == '2'" type="text" icon="Position" @click="sendCard(scope.row)">发货</el-button>
                </div>
                <div style="margin-top: 5px">
                  <el-button
                    type="text" icon="Postcard" @click="viewGainCard(scope.row)">查看中卡</el-button>
                </div>
                <div style="margin-top: 5px">
                  <el-button v-if="scope.row.logisticsStatus == '3' || scope.row.logisticsStatus == '4'"
                    type="text" icon="CreditCard" @click="viewLogistics(scope.row)">物流详情</el-button>
                </div>
                <div style="margin-top: 5px">
                  <el-button v-if="scope.row.logisticsStatus == '3'"
                    type="text" icon="Edit" @click="editLogisticsInfo(scope.row)">修改物流</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改球星卡订单对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="orderLogisticsFormRef" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看中卡对话框 -->
    <el-dialog title="查看中卡" v-model="openGainCard.visible" width="1000px" append-to-body>
      <el-table v-loading="loading" :data="reportVoList">
        <el-table-column label="卡密信息" align="center" prop="carmiInfo" />
        <el-table-column label="正面图" align="center" prop="frontImagePath" >
          <template #default="scope">
            <image-preview :src="scope.row.frontImagePath" width="100px" height="120px"></image-preview>
          </template>
        </el-table-column>
        <el-table-column label="反面图" align="center" prop="reverseImagePath">
          <template #default="scope">
            <image-preview :src="scope.row.reverseImagePath"  width="100px" height="120px"></image-preview>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="totalReport > 0" :total="totalReport" v-model:page="gainCardParams.pageNum" v-model:limit="gainCardParams.pageSize" @pagination="getGainCardList" />
    </el-dialog>

    <!-- 物流信息对话框 -->
    <el-dialog title="物流信息" v-model="openLogistics.visible" width="1100px" append-to-body>
      <el-scrollbar style="height: 650px; overflow: hidden;"
                    v-if="logisticsInformation && logisticsInformation.length > 0">
        <div
          style="display: flex;align-items: center; justify-content: flex-start;padding-left: 20px;padding-bottom: 30px;font-size: 16px;line-height: 18px;"
          v-if="logisticsInformation.length > 0">
          <div style="margin-right: 10px;"> {{ logisticsInformation[0].companyName }} </div>
          <div style="font-size: 14px;"> {{ logisticsInformation[0].number }} </div>
        </div>
        <div>
          <el-timeline :reverse="false">
            <el-timeline-item v-for="(activity, index) in logisticsInformation" :key="index" :timestamp="activity.time">
              {{ activity.status }}
            </el-timeline-item>
          </el-timeline>
        </div>
      </el-scrollbar>
      <div v-else>
        <div style="padding-left: 12px;padding-top: 12px;">
          <div>物流信息暂未更新</div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="openLogistics.visible = false ">关 闭</el-button>
      </div>
    </el-dialog>

    <!--查看订单-->
    <el-dialog title="发货" v-model="openSendCard.visible" append-to-body width="1500" :destroy-on-close="true" center>
      <sendLogistics :logisticsId="logisticsId" @subSucess="subSucess"/>
    </el-dialog>

    <!--修改物流-->
    <el-dialog title="修改物流" v-model="editLogistics.visible" append-to-body width="800" :destroy-on-close="true" center>
      <el-form :model="orderLogisticsInfo" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="快递单号" prop="expressageNumber">
              <el-input v-model="orderLogisticsInfo.expressageNumber" placeholder="请输入快递单号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="物流公司" prop="expressageComCode">
              <el-select v-model="orderLogisticsInfo.expressageComCode"  filterable @change="chooseComCode">
                <el-option v-for="item in expressageInfoListers" :key="item.id" :value="item.expressageComCode"
                           :label="item.expressageCompany"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="发货时间" prop="shipTime">
              <el-date-picker v-model="orderLogisticsInfo.shipTime" type="datetime" placeholder="请选择发货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="margin-top: 20px;">
        <el-button :loading="logisticsButtonLoading" type="primary" @click="submitDeliverGoodsForm">确 定</el-button>
        <el-button @click="editLogistics.visible = false">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script setup name="OrderLogistics" lang="ts">
import {
  listOrderLogistics,
  getOrderLogistics,
  delOrderLogistics,
  addOrderLogistics,
  updateOrderLogistics,
  queryLogisticsExpressage, getGainCardCarmiInfo, getLogisticsInfo, queryExpressageInfoList, updateLogistics
} from '@/api/system/orderLogistics';
import {
  OrderLogisticsVO,
  OrderLogisticsQuery,
  OrderLogisticsForm,
  CardOpenReportVo
} from '@/api/system/orderLogistics/types';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { logistics_status,logistics_source } = toRefs<any>(proxy?.useDict('logistics_status','logistics_source'));
import sendLogistics from '@/components/cardOrder/sendLogistics.vue';
import { ref } from 'vue';
const orderLogisticsList = ref<OrderLogisticsVO[]>([]);
const reportVoList = ref<CardOpenReportVo[]>([]);
const totalReport = ref();
const logisticsId = ref();
const buttonLoading = ref(false);
const logisticsButtonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const logisticsInformation = ref([]);

const queryFormRef = ref<ElFormInstance>();
const orderLogisticsInfo = ref({});
const orderLogisticsFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const openLogistics = reactive<DialogOption>({
  visible: false,
  title: ''
});

const openGainCard = reactive<DialogOption>({
  visible: false,
  title: ''
});

const openSendCard = reactive<DialogOption>({
  visible: false,
  title: ''
});

const editLogistics = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: OrderLogisticsForm = {
  id:undefined,
}
const data = reactive<PageData<OrderLogisticsForm, OrderLogisticsQuery>>({
  form: {...initFormData},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userId: undefined,
    logisticsStatus: '-1',
    cardOrderNumber: undefined,
    unitPrice: undefined,
    count: undefined,
    orderFreight: undefined,
    threePaymentNumber: undefined,
    sendProvince: undefined,
    sendCity: undefined,
    sendArea: undefined,
    detailAddress: undefined,
    sendName: undefined,
    sendPhone: undefined,
    cancelTime: undefined,
    payTime: undefined,
    shipTime: undefined,
    receivedTime: undefined,
    shopId: undefined,
    cardCollageId: undefined,
    collageImagePath: undefined,
    cardCollageName: undefined,
    userInviteCode: undefined,
    receivedWay: undefined,
    params: {
    }
  },
  rules: {
  }
});

const gainCardParams = reactive({
  pageNum: 1,
  pageSize: 10,
  cardOrderLogisticsId: undefined,
});

const expressageInfoListers = ref([]);

const { queryParams, form, rules } = toRefs(data);

/** 查询球星卡订单列表 */
const getList = async () => {
  loading.value = true;
  const res = await listOrderLogistics(queryParams.value);
  orderLogisticsList.value = res.rows;
  total.value = res.total;
  loading.value = false;
}

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
}

/** 表单重置 */
const reset = () => {
  form.value = {...initFormData};
  orderLogisticsFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
}

const subSucess = async() => {
  proxy?.$modal.msgSuccess("发货成功");
  openSendCard.visible = false;
  await getList();
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
}

/** 多选框选中数据 */
const handleSelectionChange = (selection: OrderLogisticsVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = "添加球星卡订单";
}

/** 修改按钮操作 */
const handleUpdate = async (row?: OrderLogisticsVO) => {
  reset();
  const _id = row?.id || ids.value[0]
  const res = await getOrderLogistics(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = "修改球星卡订单";
}

/** 提交按钮 */
const submitForm = () => {
  orderLogisticsFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      logisticsButtonLoading.value = true;
      if (form.value.id) {
        await updateOrderLogistics(form.value).finally(() =>  logisticsButtonLoading.value = false);
      } else {
        await addOrderLogistics(form.value).finally(() =>  logisticsButtonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
      dialog.visible = false;
      await getList();
    }
  });
}

/** 删除按钮操作 */
const handleDelete = async (row?: OrderLogisticsVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除球星卡订单编号为"' + _ids + '"的数据项？').finally(() => loading.value = false);
  await delOrderLogistics(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
}

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download('system/orderLogistics/export', {
    ...queryParams.value
  }, `orderLogistics_${new Date().getTime()}.xlsx`)
}

const viewLogistics = async (row?: OrderLogisticsVO) => {
  openLogistics.visible = true;
  const res = await queryLogisticsExpressage(row?.id);
  if(res.code == 200) {
    logisticsInformation.value = res.rows;
  } else {
    proxy?.$modal.alertWarning("查询失败");
  }
}

const viewGainCard = (row?: OrderLogisticsVO) => {
  openGainCard.visible = true;
  gainCardParams.cardOrderLogisticsId = row?.id;
  getGainCardList();
}

const getGainCardList = async () => {
  loading.value = true;
  const res = await getGainCardCarmiInfo(gainCardParams);
  if(res.code == 200) {
    reportVoList.value = res.rows;
    totalReport.value = res.total;
  } else {
    proxy?.$modal.msgError("查询失败");
  }
  loading.value = false;
}

const sendCard = (row?: OrderLogisticsVO) => {
  logisticsId.value = row?.id;
  openSendCard.visible = true;
}

const editLogisticsInfo = async (row?: OrderLogisticsVO) => {
  editLogistics.visible = true;
  const res = await getLogisticsInfo(row?.id);
  if(res.code == 200) {
    orderLogisticsInfo.value = res.data;
  }
  getExpressageInfoListers();
}

const getExpressageInfoListers = async () => {
  expressageInfoListers.value = [];
  const res = await queryExpressageInfoList('1');
  expressageInfoListers.value = res.data;
}

const submitDeliverGoodsForm = async () => {
  const res = await updateLogistics(orderLogisticsInfo.value);
  if(res.code == 200) {
    editLogistics.visible = false;
    proxy?.$modal.msgSuccess("修改成功");
  }
  await getList();
}

const chooseComCode = () => {
  expressageInfoListers.value.forEach((item: any) => {
    if(item.expressageComCode == orderLogisticsInfo.value.expressageComCode) {
      orderLogisticsInfo.value.expressageComCode = item.expressageComCode;
      orderLogisticsInfo.value.expressageCompany = item.expressageCompany;
    }
  })
}

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.main-order-header {
  margin-top: 10px;
  display: flex;
  height: 35px;
  background-color: #F0F0F0;
  border: 1px solid #BBBBBB;
  line-height: 40px;
  font-size: 15px;
  color: gray;
  text-align: center;
  flex-direction: row
}
</style>
